package com.refusea.train.domain.helper

import com.refusea.train.domain.cache.CourseCache
import com.refusea.train.domain.cache.RichTextCache
import com.refusea.train.domain.cache.SchoolCache
import com.refusea.train.domain.cache.UserCache
import com.refusea.train.domain.entity.RichText.Cat
import com.refusea.train.domain.entity.RichText.Cat.COURSE
import com.refusea.train.domain.entity.RichText.Cat.TEACHER
import com.refusea.train.domain.entity.User.Role.PRINCIPAL
import com.refusea.train.utils.Codes
import org.springframework.stereotype.Component
import org.springframework.ui.Model

/**
 * @author Zhang Yan 2024/5/3
 **/
@Component
class TemplateHelper(
    private val schoolCache: SchoolCache,
    private val userCache: UserCache,
    private val courseCache: CourseCache,
    private val richTextCache: RichTextCache,
) {

    fun getTemplate(cat: Cat, code: String, id: Int, model: Model): String {

        val (referrerId, schoolId) = Codes.decode(code)

        val school = schoolCache.get(schoolId) ?: return "index"


        val entityId: Int
        when (cat) {
            TEACHER -> {
                val teachers = userCache.teachers(schoolId)
                if (teachers.isEmpty()) {
                    return "index"
                }

                entityId = if (id == 0) {
                    (teachers.firstOrNull { it.role == PRINCIPAL } ?: teachers.first()).id
                } else {
                    id
                }

                if (teachers.size > 1) {
                    model.addAttribute("subMenu", teachers.map {
                        SubMenu("/teacher/${code}?id=${it.id}", it.name, it.id == entityId)
                    })
                }
            }

            COURSE -> {
                val courses = courseCache.list(schoolId)
                if (courses.isEmpty()) {
                    return "index"
                }
                entityId = if (id == 0) {
                    courses.first().id
                } else {
                    id
                }
                if (courses.size > 1) {
                    model.addAttribute("subMenu", courses.map {
                        SubMenu("/course/${code}?id=${it.id}", it.name, it.id == entityId)
                    })
                }
            }

            else -> entityId = 0
        }

        val content = richTextCache.get(schoolId, cat, entityId)?.content ?: "empty"

        model.addAttribute("title", school.name)
        model.addAttribute("content", content)
        model.addAttribute("code", code)

        model.addAttribute("schoolUrl", "/school/$code")
        model.addAttribute("teacherUrl", "/teacher/$code")
        model.addAttribute("courseUrl", "/course/$code")

        model.addAttribute("cat", cat)

        return "page"
    }

    data class SubMenu(val url: String, val name: String, val active: Boolean = false) {
        val className = if (active) "active" else ""
    }
}

